package com.dongbo.recorder.screenrecord.wxapi;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.dongbo.recorder.screenrecord.bean.WXSecond;
import com.dongbo.recorder.screenrecord.ui.activity.LoginActivity;
import com.dongbo.recorder.screenrecord.utils.Tt;
import com.google.gson.Gson;
import com.dongbo.recorder.screenrecord.Constants;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final int RETURN_MSG_TYPE_LOGIN = 1; //登录
    private static final int RETURN_MSG_TYPE_SHARE = 2; //分享
    public static String WX_LOGIN_FAILED = "WX_LOGIN_FAILED";

    private Context mContext;

    private IWXAPI api;
    private WXLoginReceiver receiver;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_wx_bg);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
        api.handleIntent(getIntent(), this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WX_LOGIN_FAILED);
        receiver = new WXLoginReceiver();
        registerReceiver(receiver, intentFilter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

//    @Override
//    public void onResp(BaseResp resp) {
//        switch (resp.errCode) {
//            case -6:
//            case BaseResp.ErrCode.ERR_AUTH_DENIED:
//            case BaseResp.ErrCode.ERR_COMM:
//            case BaseResp.ErrCode.ERR_SENT_FAILED:
//            case BaseResp.ErrCode.ERR_UNSUPPORT:
//            case BaseResp.ErrCode.ERR_USER_CANCEL:
//                break;
//            case BaseResp.ErrCode.ERR_OK:
//                switch (resp.getType()) {
//                    case RETURN_MSG_TYPE_LOGIN:
//                        //获取accesstoken
//                        String code = ((SendAuth.Resp) resp).code;
//                        getAccessToken(code);
//                        break;
//                    case RETURN_MSG_TYPE_SHARE:
//                        break;
//                }
//                break;
//        }
//        finish();
//    }

    @Override
    public void onResp(BaseResp resp) {
        //登录回调
        Log.i("mkdgskjfbksjhfis", "resp.errCode==="+resp.errCode);
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN:
                        //获取accesstoken
                        String code = ((SendAuth.Resp) resp).code;
                        Log.i("mkdgskjfbksjhfis", "code==="+code);
                        if (!TextUtils.isEmpty(code)) {
                            Intent intent = new Intent();
                            intent.putExtra(LoginActivity.WX_LOGIN_CODE, code);
                            intent.setAction(LoginActivity.WX_LOGIN_ACTION);
                            sendBroadcast(intent);
                            finish();
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra(LoginActivity.WX_LOGIN_CODE, "");
                            intent.setAction(LoginActivity.WX_LOGIN_ACTION);
                            sendBroadcast(intent);
                            WXEntryActivity.this.finish();
                        }
//                        getAccessToken(code);
                        break;
                    case RETURN_MSG_TYPE_SHARE:
                        finish();
                        break;
                }

//                String code = ((SendAuth.Resp) resp).code;
//                requestServer(2, "", code);
//                getAccessToken(code);
//                Tt.show(this, "登录成功");
//                Intent intent = new Intent();
//                intent.putExtra(LoginActivity.WX_LOGIN_CODE, code);
//                intent.setAction(LoginActivity.WX_LOGIN_ACTION);
//                sendBroadcast(intent);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                Tt.show(this, "用户取消");
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                Tt.show(this, "用户拒绝授权");
                finish();
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                Tt.show(this, "ERR_UNSUPPORT");
                finish();
                break;
            default:
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody body = new FormBody.Builder()
                .add("appid", Constants.WX_APP_ID)
                .add("secret", Constants.MM)
                .add("code", code)
                .add("grant_type", "authorization_code")
                .build();
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/sns/oauth2/access_token")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    //登录成功，保存用户信息
                    Toast.makeText(WXEntryActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    WXEntryActivity.this.finish();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                WXSecond info = null;
                try {
                    info = new Gson().fromJson(body, WXSecond.class);
                    if (info != null
                            && info.getExpires_in() == 7200) {
                        WXSecond finalInfo = info;
                        runOnUiThread(() -> {
                            //登录成功，保存用户信息
                            getUserInfo(finalInfo.getAccess_token(), finalInfo.getOpenid());
                        });
                    } else {
                        WXSecond finalInfo1 = info;
                        runOnUiThread(() -> {
                            //登录成功，保存用户信息
                            Toast.makeText(WXEntryActivity.this, finalInfo1 != null ? finalInfo1.getErrmsg() : "返回值有误",Toast.LENGTH_SHORT).show();
                            WXEntryActivity.this.finish();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    WXEntryActivity.this.finish();
                }
            }
        });

    }


    private void getUserInfo(String access, String openid) {
//        String getUserInfoUrl = "?access_token=" + access + "&openid=" + openid;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("access_token", access)
                .add("openid", openid)
                .build();
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/sns/userinfo")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    //登录成功，保存用户信息
                    Toast.makeText(WXEntryActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    WXEntryActivity.this.finish();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Intent intent = new Intent();
                intent.putExtra(LoginActivity.WX_LOGIN_CODE, responseInfo);
                intent.setAction(LoginActivity.WX_LOGIN_ACTION);
                sendBroadcast(intent);
                finish();
            }
        });
    }

    class WXLoginReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 将该app注册到微信
            api.registerApp(Constants.WX_APP_ID);
            if (intent.getAction().equals(WX_LOGIN_FAILED)) {
                WXEntryActivity.this.finish();
            }
        }
    }
}

